package com.atguigu.gmall.common.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/8/30 3:32
 */
@Slf4j
public class JsonUtil {


    public static String toStr(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            log.error("对象转json字符串失败", e);
            return null;
        }
    }

    public static String toStrNoNull(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            log.error("对象转json字符串失败", e);
            return null;
        }
    }

    public static <T> T jsonToObject(String jsonStr, TypeReference<T> typeReference) {
        ObjectMapper objectMapper = new ObjectMapper();
        T t = null;
        try {
            //objectMapper.readValue是将json字符串反序列化为对象
            //TypeReference<T> typeReference是指明了T的类型
            t = objectMapper.readValue(jsonStr, typeReference);
        } catch (JsonProcessingException e) {
            log.error("json字符串转对象失败", e);
        }
        return t;
    }
}
